package com.dunqi.gpm.cangxi.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.base.UploadFileActivity;
import com.dunqi.gpm.cangxi.common.util.FormUtil;
import com.dunqi.gpm.cangxi.common.util.JsonUtils;
import com.dunqi.gpm.cangxi.common.util.TimeUtil;
import com.dunqi.gpm.cangxi.common.view.NoScrollGridView;
import com.dunqi.gpm.cangxi.develop.widget.DrawLeftRadioButton;
import com.dunqi.gpm.cangxi.home.adapter.PhotoAdapter;
import com.dunqi.gpm.cangxi.home.bean.EarlyInfo;
import com.dunqi.gpm.cangxi.home.bean.RemarkPic;
import com.dunqi.gpm.cangxi.home.constance.Constance;
import com.dunqi.gpm.cangxi.home.widget.DatePickerDiaglog;
import com.dunqi.gpm.cangxi.home.widget.NormalView;
import com.dunqi.gpm.cangxi.mine.util.UserUtil;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

public class EarlyAuditDetailActivity extends UploadFileActivity {
    private static final String DATA = "list_photo";
    @BindView(R.id.state_name_view)
    NormalView stateNameView;
    @BindView(R.id.company_view)
    NormalView companyView;
    @BindView(R.id.company_leader_view)
    NormalView companyLeaderView;
    @BindView(R.id.company_phone_view)
    NormalView companyPhoneView;
    @BindView(R.id.audit_level_view)
    NormalView auditLevelView;
    @BindView(R.id.audit_circle_view)
    NormalView auditCircleView;
    @BindView(R.id.plan_start_time_view)
    NormalView planStartTimeView;
    @BindView(R.id.plan_complete_time_view)
    NormalView planCompleteTimeView;
    @BindView(R.id.actual_start_time_view)
    NormalView actualStartTimeView;
    @BindView(R.id.actual_complete_time_view)
    NormalView actualCompleteTimeView;
    @BindView(R.id.audit_state_view)
    NormalView auditStateView;
    @BindView(R.id.actual_complete_time_tv)
    TextView actualCompleteTimeTv;
    @BindView(R.id.remark_edit)
    EditText remarkEdit;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.commit_tv)
    DrawLeftRadioButton commitTv;

    private EarlyInfo item;
    private String actureStartTime;

//0 待申请
//1 待审核
//2 已审核
//1 待审核=待完成
//2 已审核=已完成
    String[] states = {"待申请", "待完成", "已完成"};

    @Override
    protected void refreshData(Bundle savedInstanceState) {
    }

    @Override
    protected void initUiAndListener() {
        super.initUiAndListener();
        item = (EarlyInfo) getIntent().getSerializableExtra(DATA);
        refreshUI();
    }

    private void refreshUI() {
        if (item == null) {
            return;
        }
        auditLevelView.setVisibility(View.GONE);
        auditCircleView.setVisibility(View.GONE);
        planStartTimeView.setVisibility(View.GONE);
        planCompleteTimeView.setVisibility(View.GONE);

        stateNameView.setText(item.getStageName());
        companyView.setText(item.getRespOrgName());
        companyLeaderView.setText(item.getRespOrgLeaderName());
        companyPhoneView.setText(item.getRespOrgLeaderPhone());
        auditLevelView.setText(item.getAuditLevelText());

        auditCircleView.setText(String.valueOf(item.getIntervalDays()) + "天");

        planStartTimeView.setText(TimeUtil.getTen(item.getPlanStartTime()));
        planCompleteTimeView.setText(TimeUtil.getTen(item.getPlanCompleteTime()));

        actualStartTimeView.setText(TimeUtil.getTen(item.getActualStartTime()));

        actualCompleteTimeView.setText(TimeUtil.getSeven(item.getActualCompleteTime()));

        int status = item.getStageStatus();
        auditStateView.setText(states[status]);

        /**  隐藏 实际启动时间 */
        actualStartTimeView.setVisibility(View.GONE);

        if (status == 0) {
            auditStateView.setTextColor(R.color.material_deep_orange_400);
            actualStartTimeView.setVisibility(View.GONE);
            actualCompleteTimeView.setVisibility(View.GONE);
        } else {
            container.setVisibility(View.GONE);
            commitTv.setVisibility(View.GONE);
            String auditSubmitAttachs =  item.getAuditSubmitAttachs();//item.getAudittAttachs();
//            if (TextUtils.isEmpty(auditSubmitAttachs)) {
//                auditSubmitAttachs = item.getAuditSubmitAttachs();
//            }
            if (!TextUtils.isEmpty(auditSubmitAttachs)) {
                ArrayList<RemarkPic> pics = JsonUtils.fromJson(auditSubmitAttachs, new TypeToken<ArrayList<RemarkPic>>() {
                }.getType());
                picPaths.clear();
                for (RemarkPic pic : pics) {
                    picPaths.add(UserUtil.getBaseUrl() + pic.getUrl());
                }
                PhotoAdapter adapter = new PhotoAdapter(getActivity(), picPaths);
                gridView.setAdapter(adapter);
                gridView.setVisibility(View.VISIBLE);
            } else {
                gridView.setVisibility(View.GONE);
            }
        }
    }

    public static void start(Activity context, EarlyInfo earlyInfo) {
        Intent intent = new Intent(context, EarlyAuditDetailActivity.class);
        intent.putExtra(DATA, earlyInfo);
        context.startActivityForResult(intent, 40);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_early_audit_detail;
    }

    @Override
    protected GridView getPhotoGv() {
        return gridView;
    }

    @OnClick({R.id.actual_complete_time_tv, R.id.commit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actual_complete_time_tv:
                final DatePickerDiaglog diaglog = new DatePickerDiaglog(getActivity());
                diaglog.show();
                diaglog.setCanceledOnTouchOutside(true);
                diaglog.setOnDismissListener(dialog -> {
                    actureStartTime = diaglog.getTime();
                    actualCompleteTimeTv.setText(actureStartTime);
                });
                break;
            case R.id.commit_tv:
                commit();
                break;
        }
    }

    //提交申请
    private void commit() {

        if (TextUtils.isEmpty(actureStartTime)) {
            t("实际启动实际不能为空");
            return;
        }

        HashMap<String, String> hashMap = new HashMap<>();
        ArrayList<String> photoPaths = getPhotoPaths();

        String remark = getRemark();
        String[] fileRemark = new String[photoPaths.size()];
        for (int i = 0; i < photoPaths.size(); i++) {
            fileRemark[i] = remark;
        }
        hashMap.put("fileRemark", remark);
        hashMap.put("proAnnualPlanPreStageId", String.valueOf(item.getProAnnualPlanPreStageId()));
        hashMap.put("actualStartTime", actureStartTime);

        HashMap<String, RequestBody> bodyHashMap = FormUtil.AddHeader(hashMap, "stage-file", photoPaths);

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在提交...");
        ApiFactory.getInstance()
                .startStage(bodyHashMap)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(data -> {
                    dialog.dismiss();
                    t("提交成功");
                    setResult(400);
                    finish();
                }, throwable -> {
                    dialog.dismiss();
                    t("提交失败");
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = picPaths.get(position);
        if (item == null) {
            return;
        }
        if (TextUtils.isEmpty(path)) {
            PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照， 默认false
            intent.setMaxTotal(Constance.MAX_PIC); // 最多选择照片数量，默认为9
            ArrayList<String> paths = getPhotoPaths();
            intent.setSelectedPaths(paths); // 已选中的照片地址， 用于回显选中状态
            // intent.setImageConfig(config);
            startActivityForResult(intent, Constance.REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
            if (item.getStageStatus() == 0) {
                intent.setCurrentItem(position - 1); // 当前选中照片的下标
                ArrayList<String> paths = getPhotoPaths();
                intent.setPhotoPaths(paths); // 已选中的照片地址
            } else {
                intent.setCurrentItem(position); // 当前选中照片的下标
                intent.setPhotoPaths(picPaths); // 已选中的照片地址
            }
            startActivityForResult(intent, Constance.REQUEST_PREVIEW_CODE);
        }
    }

    @Override
    @NonNull
    public ArrayList<String> getPhotoPaths() {
        ArrayList<String> paths = new ArrayList<>();
        paths.addAll(picPaths);
        if (item.getStageStatus() == 0) {
            paths.remove(0);
        } else {
        }
        return paths;
    }

    @Override
    protected void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        if (item.getStageStatus() == 0) {
            picPaths.clear();
            picPaths.add(null);
            picPaths.addAll(paths);
            getAdapter().notifyDataSetChanged();
        } else {
            picPaths.clear();
            picPaths.addAll(paths);
            getAdapter().notifyDataSetChanged();
        }
    }

    private String getRemark() {
        return remarkEdit.getText().toString().trim();
    }
}
